#include "socketio.hpp"
#include "header.h"
//#include "logger.h"
namespace moqi
{
SocketIO::SocketIO(int fd):
_fd(fd)
{

}

int SocketIO:: recvn(char * buff, int len)
{
    int left = len;
    char *pbuff = buff;
    while(left > 0)
    {
        int ret = recv(_fd, pbuff, left, 0);
        if(ret == -1)
        {
            if(errno == EINTR)
            {
                continue;
            }
            else
            {
                string str = "recvn";
                LOG_ERROR(str.c_str());
//                perror("recvn");
                return len - left;
            }

        }
        else if (ret == 0)//连接断开
        {
            return len - left;
        }
        left -= ret;
        pbuff += ret;
    }
    return len;

}

int SocketIO::sendn(const char * buff, int len)const
{
    int left = len;
    const char * pbuff = buff;
    while(left > 0)
    {
        int ret = send(_fd, pbuff, left, 0);
        if(ret < 0)//ret 大部分情况不会
        {
    //        LOG_ERROR("sendn");
            //perror("sendn");
            return len - left;
        }
        left -= ret;
        pbuff += ret;
    }
    return len;
}

int SocketIO::recvLine(char * buff, int max)
{
    int left = max- 1;
    int total = 0;
    char *pbuff = buff;
    while(left > 0)
    {
        int ret = recvPeek(pbuff, left);
        for(int i = 0; i < ret; ++i)
        {
            if(pbuff[i] == '\n')
            {
                recvn(pbuff, i+1);
                pbuff[i] = '\0';
                total += i;
                return total;
            }
        }
        ret = recvn(pbuff, ret);
        left -= ret;
        pbuff += ret;
        total += ret;
    }
    return max - 1;

}

int SocketIO::recvPeek(char *buff,int len)const
{
    int ret = -1;
    do{
        ret = recv(_fd, buff, len, MSG_PEEK);
    }while(ret == -1 && errno == EINTR);
    return ret;
}

}
